import 'package:common_utils/common_utils.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:union_pay/enum/union_pay_enum.dart';
import 'package:union_pay/model/payment_result_model.dart';
import 'package:union_pay/union_pay.dart';
import 'package:xinxuan/common/dialogs/del_dialog.dart';
import 'package:xinxuan/common/dialogs/union_pay_dialog.dart';
import 'package:xinxuan/config/app_config.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/vo/bank_card_list_vo.dart';
import 'package:xinxuan/vo/common_vo/common_bank_card_item_vo.dart';
import 'package:xinxuan/vo/order_detail_vo.dart';
import 'package:xinxuan/vo/ali_pay_vo.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:xinxuan/vo/union_pay_vo.dart';
import 'package:xinxuan/vo/wx_pay_vo.dart';
import 'dart:convert' as convert;

class StoreOrderPayPageController extends GetxController {

  final CommonPageController commonPageController = Get.find();
  /// 订单信息
  var orderDetailData = OrderDetailData(id: 0, payAmount: '0.00', payableAmount: '0.00').obs;

  /// 银行卡列表
  var payBankArr = <CommonBankCardItemVo>[].obs;

  /// 支付方式
  var payType = 0.obs;
  /// 银行卡支付，银行卡ID
  var fastPaymentId = 0.obs;
  String password = '';
  var _weChatPay;
  /// 是否为商品详情跳转支付页
  bool _isDetail = false;

  @override
  void onReady() {
    _weChatPay = fluwx.weChatResponseEventHandler.listen((event) async {
      if (event.errCode == 0) {
        if (_isDetail) {
          Get.offAndToNamed(
            '${AppRouters.COMMON_PAGE}${AppRouters.PAY_SUCCESS_PAGE}',
            arguments: {
              'orderId': orderDetailData.value.id,
              'isDetail': _isDetail
            }
          );
        } else {
          Get.toNamed(
            '${AppRouters.COMMON_PAGE}${AppRouters.PAY_SUCCESS_PAGE}',
            arguments: {
              'orderId': orderDetailData.value.id,
              'isDetail': _isDetail,
              'result': true
            }
          )!.then((res) {
            if (res != null && res) {
              Get.back(result: true);
            }
          });
        }
      }
    });
    UnionPay.payListener((PaymentResult result) {
      if (result.code != 1) {
        return;
      }
      if (_isDetail) {
        Get.offAndToNamed(
          '${AppRouters.COMMON_PAGE}${AppRouters.PAY_SUCCESS_PAGE}',
          arguments: {
            'orderId': orderDetailData.value.id,
            'isDetail': _isDetail
          }
        );
      } else {
        Get.toNamed(
          '${AppRouters.COMMON_PAGE}${AppRouters.PAY_SUCCESS_PAGE}',
          arguments: {
            'orderId': orderDetailData.value.id,
            'isDetail': _isDetail,
            'result': true
          }
        )!.then((res) {
          if (res != null && res) {
            Get.back(result: true);
          }
        });
      }
    });
    initPageDate();
    super.onReady();
  }

  initPageDate() {
    Map<String, dynamic> argumentsMap = Get.arguments;
    int orderId = argumentsMap['orderId'];
    EasyLoading.show();
    Future.wait([
      getOrderDetail(orderId),
      getPayBankList()
    ]).then((results){
      orderDetailData.value = results[0] as OrderDetailData;
      payBankArr.value = results[1] as List<CommonBankCardItemVo>;
      update();
      EasyLoading.dismiss();
    }).catchError((e){
      EasyLoading.dismiss();
    });
  }

  /// 获取用户支付银行卡列表
  Future<List<CommonBankCardItemVo>> getPayBankList() async {
    BankCardListVo payBankListVo = await HttpUtilService.getPayBankList(loading: false);
    return payBankListVo.data!;
  }

  /// 获取订单详情
  Future<OrderDetailData> getOrderDetail(int orderId) async {
    OrderDetailVo orderDetailVo = await HttpUtilService.getStoreOrderDetail(orderId: orderId, loading: false);
    return orderDetailVo.data!;
  }
  
  /// 确认支付
  confirmPay(bool isDetail) {
    _isDetail = isDetail;
    if (payType.value == 0) {
      aliPay(orderDetailData.value.orderSn!);
    } else if (payType.value == 1) {
      wxPay(orderDetailData.value.orderSn!);
    } else if (payType.value == 2) {
      unionPay(orderDetailData.value.orderSn!);
    } else {
      _bankPay(orderDetailData.value.orderSn!);
    }
  }

  /// 支付宝支付
  aliPay(String orderSn) async {
    bool isAliPayInstalled = await tobias.isAliPayInstalled();
      if (!isAliPayInstalled) {
        EasyLoading.showToast('请先安装支付宝');
        return;
      }
    AliPayVo? aliPayVo = await HttpUtilService.aliPay(orderSn: orderSn, orderType: 2);
    if (aliPayVo != null) {
      Map<dynamic, dynamic> res = await tobias.aliPay(aliPayVo.data!);
      if (!TextUtil.isEmpty(res['result'])) {
        Map<String, dynamic> map = convert.jsonDecode(res['result']);
        Map<String, dynamic> alipayTradeAppPayResponse = convert.jsonDecode(convert.jsonEncode(map['alipay_trade_app_pay_response']));
        if (alipayTradeAppPayResponse['code'] == '10000') {
          if (_isDetail) {
            Get.offAndToNamed(
              '${AppRouters.COMMON_PAGE}${AppRouters.PAY_SUCCESS_PAGE}',
              arguments: {
                'orderId': orderDetailData.value.id,
                'isDetail': _isDetail
              }
            );
          } else {
            Get.toNamed(
              '${AppRouters.COMMON_PAGE}${AppRouters.PAY_SUCCESS_PAGE}',
              arguments: {
                'orderId': orderDetailData.value.id,
                'isDetail': _isDetail,
                'result': true
              }
            )!.then((res) {
              if (res != null && res) {
                Get.back(result: true);
              }
            });
          }
        }
      }
    }
  }

  /// 微信支付
  wxPay(String orderSn) async {
    await fluwx.registerWxApi(
      appId: AppConfig.wxAppId,
      universalLink: AppConfig.universalLink
    );
    bool isWeChatInstalled = await fluwx.isWeChatInstalled;
    if (!isWeChatInstalled) {
      EasyLoading.showToast('请先安装微信');
      return;
    }
    WxPayVo? wxPayVo = await HttpUtilService.wxPay(orderSn: orderSn, orderType: 2);
    if (wxPayVo != null) {
      fluwx.payWithWeChat(
        appId: wxPayVo.data!.appid!, 
        partnerId: wxPayVo.data!.partnerid!, 
        prepayId: wxPayVo.data!.prepayid!, 
        packageValue: wxPayVo.data!.package!, 
        nonceStr: wxPayVo.data!.noncestr!, 
        timeStamp: wxPayVo.data!.timestamp!, 
        sign: wxPayVo.data!.sign!
      );
    }
  }

  /// 银行卡支付
  _bankPay(String orderSn) async {
    if (commonPageController.userData.value.isPayPassword == 0) {
      Get.dialog(DelDialog(
        message: '请先设置支付密码', 
        onTap: () {
          Get.toNamed(
            '${AppRouters.COMMON_PAGE}${AppRouters.MY_INFO_PAGE}${AppRouters.UPDATE_PAY_PASSWORD_PAGE}',
            arguments: {
              'type': 1
            }
          );
        }
      ));
      return;
    }
    Get.dialog(
      UnionPayDialog(payPrice: '${orderDetailData.value.payableAmount}', onSubmitted: (value) async {
        password = value;
        Get.back();
        bool res = await HttpUtilService.bankPay(orderSn: orderSn, orderType: 2, fastPaymentId: fastPaymentId.value, password: password);
        if (res) {
          if (_isDetail) {
            Get.offAndToNamed(
              '${AppRouters.COMMON_PAGE}${AppRouters.PAY_SUCCESS_PAGE}',
              arguments: {
                'orderId': orderDetailData.value.id,
                'isDetail': _isDetail
              }
            );
          } else {
            Get.toNamed(
              '${AppRouters.COMMON_PAGE}${AppRouters.PAY_SUCCESS_PAGE}',
              arguments: {
                'orderId': orderDetailData.value.id,
                'isDetail': _isDetail,
                'result': true
              }
            )!.then((res) {
              if (res != null && res) {
                Get.back(result: true);
              }
            });
          }
        }
      }),
      barrierDismissible: false
    );
  }

  /// 云闪付支付
  unionPay(String orderSn) async {
    print('orderSn: $orderSn');
    if (!await UnionPay.isInstalled()) {
      EasyLoading.showToast('请先安装云闪付');
      return;
    }
    UnionPayVo? unionPayVo = await HttpUtilService.unionPay(orderSn: orderSn, orderType: 1);
    if (unionPayVo == null || unionPayVo.data!.isEmpty) {
      EasyLoading.showToast('提交支付异常');
      return;
    }
    await UnionPay.pay(tn: '${unionPayVo.data}', mode: PaymentEnv.PRODUCT, scheme: 'UnionPayTest');
  }

  @override
  void onClose() {
    if (_weChatPay != null) {
      _weChatPay.cancel();
    }
    super.onClose();
  }
}